package com.shouhuobao.bhi.receiver;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.baidu.location.BDLocation;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.GeneralBasicParams;
import com.baidu.ocr.sdk.model.GeneralResult;
import com.baidu.ocr.sdk.model.WordSimple;
import com.baidu.speech.EventListener;
import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;
import com.collectplus.express.R;
import com.collectplus.express.app.Animator;
import com.collectplus.express.city.ChooseAreaActivity;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.ReceiverBean;
import com.collectplus.express.model.ReceiverInfoBean;
import com.collectplus.express.model.SameCityHistoryBean;
import com.collectplus.express.model.SenderBean;
import com.collectplus.express.model.UserBean;
import com.collectplus.express.parcel.LargePicturePreviewActivity;
import com.collectplus.express.tools.BitmapUtil;
import com.collectplus.express.tools.ContactUtils;
import com.collectplus.express.tools.LengthInputFilter;
import com.collectplus.express.tools.TextWatcherExt;
import com.collectplus.express.view.SonicSensorView;
import com.collectplus.express.wxapi.Constants;
import com.shouhuobao.bhi.loc.BaiduLocationService;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

import droid.frame.app.Callback;
import droid.frame.ui.dialog.AppDialog;
import droid.frame.ui.utils.Utils;
import droid.frame.umeng.UMeng;
import droid.frame.utils.android.Alert;
import droid.frame.utils.android.Log;
import droid.frame.utils.lang.JsonParser;
import droid.frame.utils.lang.Str;
import droid.frame.view.InputFilterExt;

/**
 * 收件人-新增
 *
 * @author coffee<br>
 * 2015-6-12下午2:12:09
 */
public class ReceiverNewFragment extends ReceiverAddBaseFragment implements OnClickListener, EventListener {

    private EditText mNameEdit, mMobileEdit, mAddressEdit, mAddressDetailEdit;

    private Button mButton;
    private ReceiverBean receiver;

    private EditText mStickAddressContent;// 粘贴板的地址
    /**
     * 添加收件人 true<br>
     * 添加寄件人 false
     */
    private boolean isReceiver = true;

    private String picPath;
    private View mLoadItem;
    private View mThumbnailItem;
    private Button mInputBT;
    /**
     * 粘贴板信息
     */
    private String receiverInfo;

    /**
     * 寄送省
     */
    private final String[] province = {"北京", "天津", "上海", "重庆", "河北", "山西", "辽宁", "吉林", "黑龙江", "江苏", "浙江", "安徽", "福建", "江西", "山东", "河南",
            "湖北", "湖南", "广东", "海南", "四川", "贵州", "云南", "山西", "甘肃", "青海", "台湾", "内蒙古", "广西", "西藏", "宁夏", "新疆", "香港", "澳门"};

    /**
     * 语音识别相关
     */
    private EventManager mEventManager;
    private String mSpeekContent;//语音录入讲话内容
    private StringBuilder stringBuilder = new StringBuilder();

    /**
     * 图片识别相关
     */
    //标记是否获取到识别图片的token
    private boolean hasGotToken = false;
    // 软键盘的显示状态
    private boolean isShowKeyboard;
    private SonicSensorView mSonicSensorView;
    //智能输入中间的布局
    private ViewGroup mInputLayout;
    //语音录入时候的布局
    private ViewGroup mVoiceInputLayout;
    private ScrollView mScrollView;
    LinearLayout.LayoutParams layoutParams = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void findViewById() {
        setContentView(R.layout.receiver_new);
        super.findViewById();
        mEventManager = EventManagerFactory.create(getActivityContext(), "asr");
        mEventManager.registerListener(this);
        receiver = AppCache.getParcelNew();
        if (receiver == null) {
            receiver = new ReceiverBean();
            AppCache.setParcelNew(receiver);
        }
        isReceiver = ((ReceiverTabFragmentActivity) getActivityContext()).isReceiver();
        mScrollView = (ScrollView) findViewById(R.id.content_layout);
        mNameEdit = (EditText) findViewById(R.id.receiver_name);
        mMobileEdit = (EditText) findViewById(R.id.receiver_mobile);
        mAddressEdit = (EditText) findViewById(R.id.receiver_address);
        mAddressEdit.setOnClickListener(this);
        mAddressDetailEdit = (EditText) findViewById(R.id.receiver_address_detail);
        mButton = (Button) findViewById(R.id.receiver_new_sure);
        setButtonEnableStyle(mButton, false, 0);
        findViewById(R.id.speek_tv).setOnClickListener(this);
        //智能填写
        mInputLayout = (ViewGroup) findViewById(R.id.middle_layout);
        layoutParams = (LinearLayout.LayoutParams) mInputLayout.getLayoutParams();
        mInputBT = (Button) findViewById(R.id.input_bt);
        mInputBT.setOnClickListener(this);
        setButtonEnableStyle(mInputBT, false, 1);
        //语音录入布局
        mVoiceInputLayout = (ViewGroup) findViewById(R.id.voice_input_layout);
        findViewById(R.id.voice_cancel_tv).setOnClickListener(this);
        mSonicSensorView = (SonicSensorView) findViewById(R.id.sonicsensor_view);
        initBerzerParam(false);
        //点击展开只能地址填写
        findViewById(R.id.hide_or_show_layout).setOnClickListener(this);
        mMobileEdit.setFilters(new InputFilter[]{new InputFilterExt(1),//
                new LengthInputFilter(mMobileEdit, 11).setInputCallback(inputCallback)});
        mNameEdit.setFilters(new InputFilter[]{new InputFilterExt(0), new LengthInputFilter(mNameEdit, 10).setInputCallback(inputCallback)});
        mAddressDetailEdit.setFilters(new InputFilter[]{new InputFilterExt(4), new LengthInputFilter(mAddressDetailEdit, 50).setInputCallback(inputCallback)});
        ImageView icon = (ImageView) findViewById(R.id.receiver_address_arrow_right);
        icon.setOnClickListener(this);
        //智能填写说明
        findViewById(R.id.brainpower_input_tv).setOnClickListener(this);
        if (isReceiver == false) {
            ((TextView) findViewById(R.id.receive_name_title_tv)).setText("寄件姓名：");
            mAddressDetailEdit.setBackground(null);
            mButton.setText("确认寄件人");
            //
            mNameEdit.addTextChangedListener(textWatcher2);
            mMobileEdit.addTextChangedListener(textWatcher2);
            mAddressDetailEdit.addTextChangedListener(textWatcher2);
            SenderBean senderBean = AppCache.getSenderBean();
            if (senderBean == null) {
                UserBean user = AppCache.getUser();
                if (user != null) {
                    mNameEdit.setText(Str.filter(user.getName()));
                    mMobileEdit.setText(user.getPhone());
                }
            }
            if (receiver != null) {
                SenderBean sender = receiver.getSender();
                if (sender != null) {
                    mNameEdit.setText(Str.filter(sender.getName()));
                    mMobileEdit.setText(sender.getPhone());
                    if (isEmpty(sender.getProvince()) || isEmpty(sender.getCity()) || isEmpty(sender.getDistrict())) {
                        // 不做处理
                    } else {
                        String address = sender.getProvince() + " " + sender.getCity() + " " + sender.getDistrict();
                        mAddressEdit.setText(address);
                    }
                    mAddressDetailEdit.setText(Str.filter(sender.getAddress()));
                }
            }
        } else {
            ((TextView) findViewById(R.id.receive_name_title_tv)).setText("收件姓名：");
            mNameEdit.addTextChangedListener(textWatcher);
            mMobileEdit.addTextChangedListener(textWatcher);
            mAddressDetailEdit.addTextChangedListener(textWatcher);

            mButton.setText("确认收件人");
            // 默认收件人在layout设置好
            if (receiver != null) {
                mNameEdit.setText(Str.filter(receiver.getName()));
                mMobileEdit.setText(receiver.getPhone());
                String address = receiver.getProvince() + " " + receiver.getCity() + " " + receiver.getDistrict();
                // 如果城市区id非法、则需要用户重新填
                if (TextUtils.isEmpty(receiver.getProvinceId()) //
                        || TextUtils.isEmpty(receiver.getCityId()) || TextUtils.isEmpty(receiver.getDistrictId())) {
                    address = null;
                }
                mAddressEdit.setText(address);
                mAddressDetailEdit.setText(Str.filter(receiver.getAddress()));
            }
        }
        // 处理粘贴板
        handleClip();

        // set event
        mButton.setOnClickListener(this);
        findViewById(R.id.receiver_contact).setOnClickListener(this);

        mNameEdit.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER;
            }
        });
        mAddressDetailEdit.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER;
            }
        });
        // 加载图片
        mLoadItem = findViewById(R.id.load_local_img_item);
        mLoadItem.setOnClickListener(this);

        mThumbnailItem = findViewById(R.id.thumbnail_view);
        mThumbnailItem.setOnClickListener(this);
        //语音录入方法
        speekInputData();
        // 请选择您的初始化方式
        initAccessTokenWithAkSk();
    }

    /**
     * 初始化
     */
    private void initBerzerParam(boolean start) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setAntiAlias(true);
        if (start) {
            paint.setColor(Color.parseColor("#F5A623"));
            paint.setStrokeWidth(Utils.dpToPx(1, getResources()));
        } else {
            paint.setColor(getResources().getColor(R.color.transparent));
        }
        paint.setStyle(Paint.Style.STROKE);
        mSonicSensorView.setBezierPaint(paint);
    }

    /**
     * 初始化图片识别转化为文字
     */
    private void initAccessTokenWithAkSk() {
        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                showToast("初始化错误");
            }
        }, getActivityContext(), Constants.OCR_API_KEY, Constants.OCR_SECRET_KEY);
    }

    /**
     * 输入文字的时候会调用该方法
     */
    private LengthInputFilter.InputCallback inputCallback = new LengthInputFilter.InputCallback() {

        @Override
        public void onCallback(EditText editText) {
            if (editText == mNameEdit && mNameEdit.length() > 10) {
                showToast("最多只能输入10个字哦");
            }
            if (editText == mMobileEdit && mMobileEdit.length() > 11) {
                showToast("最多只能输入11个字哦");
            }
            if (editText == mAddressDetailEdit && mAddressDetailEdit.length() > 50) {
                showToast("最多只能输入50个字哦");
            }
        }
    };

    private TextWatcherExt textWatcher = new TextWatcherExt() {
        public void afterTextChanged(Editable s) {
            if (mNameEdit.getText().toString().trim().length() > 0 && mMobileEdit.getText().toString().trim().length() > 0 //
                    && mAddressEdit.getText().toString().trim().length() > 0 && mAddressDetailEdit.getText().toString().trim().length() > 0) {
                setButtonEnableStyle(mButton, true, 0);
            } else {
                mScrollView.scrollTo(0, mScrollView.getBottom());
                setButtonEnableStyle(mButton, false, 0);
            }
        }
    };

    private TextWatcherExt textWatcher2 = new TextWatcherExt() {
        public void afterTextChanged(Editable s) {
            if (mNameEdit.getText().toString().trim().length() > 0
                    && mMobileEdit.getText().toString().trim().length() > 0
                    && mAddressEdit.getText().toString().trim().length() > 0
                    && mAddressDetailEdit.getText().toString().trim().length() > 0) {
                setButtonEnableStyle(mButton, true, 0);
            } else {
                mScrollView.scrollTo(0, mScrollView.getBottom());
                setButtonEnableStyle(mButton, false, 0);
            }
        }

    };

    // app是否首次打开
    boolean isFirst = true;

    /**
     * 是否加载了图片
     */
    public void onResume() {
        super.onResume();
        //暂时先把下面的注释掉，不需要每次进来都进行自动识别粘贴面板里面的东西
        try {
            ClipboardManager cm = (ClipboardManager) getActivityContext().getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clipData = cm.getPrimaryClip();
            // 需要判断粘贴板是否为空
            if (clipData != null && clipData.getItemCount() > 0) {
                String str = clipData.getItemAt(0).getText().toString();
                String saveData = getSharedPref("cliptext");
                if (!stringEquale(str, saveData)) {
                    //                            parseReceiverInfo(str);
                    showReceiverInformation(str);
                    // 为了退出进来进行对比，报错复制类容
                    setSharedPref("cliptext", str);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 字符串对比
     *
     * @param str1
     * @param str2
     * @return
     */
    private boolean stringEquale(String str1, String str2) {
        if (str1 == null || str2 == null)
            return false;
        if (str1.trim().equals(str2.trim()))
            return true;
        return false;
    }

    //    /**
    //     * 收件人个人信息解析
    //     *
    //     * @param info
    //     */
    //    private void parseReceiverInfo(String info) {
    //        String punc = "[,，。.、;；\\s]";
    //        String address = "";
    //        for (int i = 0; i < province.length; i++) {
    //            boolean contains = info.contains(province[i]);
    //            if (contains) {
    //                int addressStart = info.indexOf(province[i]);
    //                // 现记录地址，防止后面没有符号
    //                address = info.substring(addressStart);
    //                Pattern compile = Pattern.compile(punc);
    //                Matcher matcher = compile.matcher(info);
    //                if (matcher.find()) {
    //                    String puucFind = matcher.group();
    //                    int puucStart = address.indexOf(puucFind);
    //                    if (puucStart != -1) {
    //                        int addressEnd = addressStart + puucStart;
    //                        address = info.substring(addressStart, addressEnd);
    //                    }
    //                }
    //                break;
    //            }
    //        }
    //        String phone = phoneFormat(info);
    //        String name = NameUtile.getName(info, address);
    //        // String name = info.substring(phoneStart + 1, phoneEnd);
    //        if (!Str.isEmpty(address) || !Str.isEmpty(phone) || !Str.isEmpty(name)) {
    //            showReceiverInformation(address, phone, name);
    //        } else {
    //            showToast("识别失败");
    //        }
    //    }

    //    /**
    //     * 匹配手机号
    //     *
    //     * @param str
    //     * @return
    //     */
    //    private String phoneFormat(String str) {
    //        Pattern p = Pattern.compile("(\\+86|86|0086)?(13[0-9]|15[0-35-9]|14[57]|18[0-9])\\d{8}");
    //        Matcher m = p.matcher(str);
    //        String phone = "";
    //        if (m.find()) {
    //            phone = m.group();
    //        }
    //        return phone;
    //    }

    @Override
    public void onStop() {
        super.onStop();
        isFirst = false;
    }

    /**
     * TODO 兼容api 15
     */
    @SuppressLint("NewApi")
    private void handleClip() {
        // 粘贴板收起\下拉按钮
        // mStickImage = (ImageView) findViewById(R.id.stick_address_icon);
        // mStickImage.setOnClickListener(this);
        final TextView cleanTV = (TextView) findViewById(R.id.text_num_tip_tv);
        cleanTV.setOnClickListener(this);
        mStickAddressContent = (EditText) findViewById(R.id.stick_address_content);
        mStickAddressContent.addTextChangedListener(new TextWatcherExt() {
            @Override
            public void afterTextChanged(Editable s) {
                UMeng.click(getActivityContext(), "receiver_stick_address_click");
                // 文本类容与粘贴板一样是弹出提示框
                if (Str.isEmpty(s)) {
                    cleanTV.setVisibility(View.GONE);
                    setButtonEnableStyle(mInputBT, false, 1);
                    if (Str.isNotEmpty(stringBuilder)) {
                        stringBuilder.delete(0, stringBuilder.length());
                    }
                    return;
                }
                cleanTV.setVisibility(View.VISIBLE);
                //                if (!Str.isEmpty(s.toString()) && stringEquale(s.toString(), getSharedPref("cliptext"))) {
                //                    //                    parseReceiverInfo(s.toString());
                //
                //                }
                if (Str.isNotEmpty(stringBuilder.toString())) {
                    stringBuilder.delete(0, stringBuilder.length());
                }
                setButtonEnableStyle(mInputBT, true, 1);
                if (s.length() > 100) {
                    stringBuilder.append(s.toString().substring(0, 100));
                } else {
                    stringBuilder.append(s.toString());
                }
                Log.d("11111", stringBuilder.toString());
            }
        });
//        try {
        // mStickAddressContent.setMovementMethod(new ScrollingMovementMethod());
        // mStickAddressContent.setOnTouchListener(new OnTouchListener() {
        // public boolean onTouch(View v, MotionEvent event) {
        // int lineDiff = mStickAddressContent.getLayout().getLineCount() - mStickAddressContent.getMaxLines();
        // if (lineDiff > 0) {
        // // 这句话说的意思告诉父View我自己的事件我自己处理
        // v.getParent().requestDisallowInterceptTouchEvent(true);
        // switch (event.getAction() & MotionEvent.ACTION_MASK) {
        // case MotionEvent.ACTION_UP:
        // v.getParent().requestDisallowInterceptTouchEvent(false);
        // break;
        // }
        // }
        // return false;
        // }
        // });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onClick(View v) {
        if (v.getId() != R.id.speek_tv) {
            mVoiceInputLayout.setVisibility(View.GONE);
        }
        Intent intent = null;
        switch (v.getId()) {
            //智能填写说明
            case R.id.brainpower_input_tv:
                DialogMgr.showBrainpowerInputTip(getActivityContext());
                break;
            //智能填写
            case R.id.input_bt:
                if (Str.isNotEmpty(stringBuilder) && Str.isNotEmpty(mStickAddressContent.getText().toString().trim())) {
                    //                    parseReceiverInfo(stringBuilder.toString());
                    showLoadingDialog(null);
                    AppHttp.getInstance().getReceiverInfoParse(mStickAddressContent.getText().toString().trim());
                } else {
                    showToast("请选择要识别的内容");
                }
                break;
            // 查看原图
            case R.id.thumbnail_view:
                intent = new Intent(getActivity(), LargePicturePreviewActivity.class);
                intent.putExtra("type", 1);
                intent.putExtra("picUrl", picPath);
                startActivityForResult(intent, 1005);
                break;
            // 打开相册、选取图片
            case R.id.load_local_img_item:
                UMeng.click(getActivityContext(), "receiver_load_local_img_click");
                //                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //                startActivityForResult(intent, 1003);
                intent = new Intent(getActivityContext(), ReceiverCameraActivity2.class);
                startActivityForResult(intent, 1006);
                break;
            //选择省市区
            case R.id.receiver_address:
                intent = new Intent(getActivity(), ChooseAreaActivity.class);
                startActivityForResult(intent, 1001);
                break;
            // 从通讯录中添加
            case R.id.receiver_contact:
                intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setData(ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, 1002);
                break;
            // 选取地址
            case R.id.receiver_address_arrow_right:
                // PackageManager pm = getActivityContext().getPackageManager();
                // boolean permission = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.ACCESS_FINE_LOCATION", App.get));
                // if (permission) {
                // showToast("有这个权限");
                // } else {
                // showToast("木有这个权限");
                // }
                int permission = ContextCompat.checkSelfPermission(getActivityContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 请求权限
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1000);
                    // 判断是否需要 向用户解释，为什么要申请该权限
                    // ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS);
                } else {
                    showLoadingDialog(null);
                    intent = new Intent();
                    intent.setClass(getActivityContext(), BaiduLocationService.class);
                    intent.putExtra("msgId", MsgID.location_receiver_new);
                    getActivityContext().startService(intent);
                }
                break;
            case R.id.receiver_new_sure:
                String name = mNameEdit.getText().toString();
                String phone = mMobileEdit.getText().toString();
                String address = mAddressDetailEdit.getText().toString();
                if (!TextUtils.isEmpty(name) && name.length() > 10) {
                    showToast("姓名最多只能输入10个字");
                    return;
                }
                if (!TextUtils.isEmpty(phone) && phone.length() > 11) {
                    showToast("联系电话最多只能输入11个字");
                    return;
                }
                if (!TextUtils.isEmpty(address) && address.length() > 50) {
                    showToast("详细地址最多只能输入50个字");
                    return;
                }
                // 收件人
                if (isReceiver) {
                    if (TextUtils.isEmpty(name)) {
                        showToast("请输入收件人姓名");
                        return;
                    }

                    if (TextUtils.isEmpty(phone.trim())) {
                        showToast("请输入收件人手机号");
                        return;
                    }

                    if (TextUtils.isEmpty(address)) {
                        showToast("请输入收件人详细地址");
                        return;
                    }
                    if (receiver == null || TextUtils.isEmpty(receiver.getProvinceId()) //
                            || TextUtils.isEmpty(receiver.getCityId()) || TextUtils.isEmpty(receiver.getDistrictId())) {
                        showToast("请选择收件人省市区");
                        return;
                    }
                    // 寄件人信息
                    receiver.setName(name);
                    receiver.setPhone(phone);
                    receiver.setAddress(address);// 详细地址
                    UMeng.click(getActivityContext(), "receiver_submit_click");
                } else {// 寄件人
                    if (TextUtils.isEmpty(name)) {
                        showToast("请输入寄件人姓名");
                        return;
                    }
                    if (TextUtils.isEmpty(phone.trim())) {
                        showToast("请输入寄件人手机号");
                        return;
                    }
                    if (TextUtils.isEmpty(address)) {
                        showToast("请输入寄件人详细地址");
                        return;
                    }
                    if (receiver == null || receiver.getSender() == null || TextUtils.isEmpty(receiver.getSender().getProvinceId()) //
                            || TextUtils.isEmpty(receiver.getSender().getCityId()) || TextUtils.isEmpty(receiver.getSender().getDistrictId())) {
                        showToast("请选择寄件人省市区");
                        return;
                    }
                    SenderBean sender = receiver.getSender();
                    if (sender == null) {
                        sender = new SenderBean();
                    }
                    sender.setName(name);
                    sender.setPhone(phone);
                    if (Str.isNotEmpty(mAddressEdit.getText())) {
                        String[] addrs = mAddressEdit.getText().toString().trim().split(" ");
                        if (addrs.length == 3) {
                            sender.setProvince(addrs[0]);
                            sender.setCity(addrs[1]);
                            sender.setDistrict(addrs[2]);
                        }
                    }
                    sender.setAddress(address);// 详细地址
                    receiver.setSender(sender);
                }

//                ReceiverBean item = receiver;
//                // 标准上门寄件
//                if (item.isGoHomeStandard()) {
//                    intent = new Intent();
//                    intent.setClass(getActivityContext(), ExpressCompanyActivity.class);
//                    intent.putExtra("item", receiver);
//                    startActivityForResult(intent, 1004);
//                } else {
                Intent data = new Intent();
                // data.putExtra("receiver", item);
                getActivityContext().setResult(Activity.RESULT_OK, data);
                getActivityContext().finish();
//                }
                break;
            //录音，点击取消语音识别
            case R.id.voice_cancel_tv:
                mVoiceInputLayout.setVisibility(View.GONE);
                break;
            //点击语音识别按钮，展示出语音录入布局
            case R.id.speek_tv:
                if (mVoiceInputLayout.getVisibility() == View.GONE) {
                    mVoiceInputLayout.setVisibility(View.VISIBLE);
                    findViewById(R.id.bottom_layout).setVisibility(View.GONE);
                    Animator.scaleY(mVoiceInputLayout, new Callback() {
                        @Override
                        public void execute(Object... result) {
                            mScrollView.scrollTo(0, mScrollView.getBottom());
                        }
                    }, 0, Utils.dpToPx(255, getResources()));
                }
                break;
            //点击展开或关闭只能地址填写
            case R.id.hide_or_show_layout:
                int height = 0;
                if (mThumbnailItem.getVisibility() == View.GONE) {
                    height = Utils.dpToPx(245, getResources());
                } else {
                    height = Utils.dpToPx(245, getResources()) + Utils.dpToPx(142, getResources());//findViewById(R.id.thumbnail_view1).getHeight()
                }
                layoutParams.height = height;
                mInputLayout.setLayoutParams(layoutParams);
                TextView receiverDownTV = (TextView) findViewById(R.id.receiverdown_tv);
                //没有展开则进行展开
                if (mInputLayout.getVisibility() == View.GONE) {
                    mInputLayout.setVisibility(View.VISIBLE);
                    receiverDownTV.setText("点击收起");
                    Drawable drawableRight = getResources().getDrawable(R.drawable.self_drawer_up_blue_icon);
                    receiverDownTV.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
                    receiverDownTV.setCompoundDrawablePadding(Utils.dpToPx(5, getResources()));
                    //                    mReceiverDown.setImageDrawable(getResources().getDrawable(R.drawable.drawer_up));
                    Animator.scaleY(mInputLayout, new Callback() {
                        @Override
                        public void execute(Object... result) {
                            mScrollView.scrollTo(0, mScrollView.getBottom());
                        }
                    }, 0, height);
                } else {
                    mVoiceInputLayout.setVisibility(View.GONE);
                    findViewById(R.id.bottom_layout).setVisibility(View.VISIBLE);
                    receiverDownTV.setText("智能地址填写");
                    Drawable drawableRight = getResources().getDrawable(R.drawable.self_drawer_down_blue_icon);
                    receiverDownTV.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
                    receiverDownTV.setCompoundDrawablePadding(Utils.dpToPx(5, getResources()));
                    mInputLayout.setVisibility(View.GONE);
                    Animator.scaleY(mInputLayout, null, height, 0);
                }
                break;
            //点击情况文本空
            case R.id.text_num_tip_tv:
                if (!isEmpty(stringBuilder.toString())) {
                    stringBuilder.delete(0, stringBuilder.length());
                }
                mStickAddressContent.setTag(null);
                mStickAddressContent.setText(null);
                setButtonEnableStyle(mInputBT, false, 1);
                break;
            // case R.id.stick_address:
            // 地址粘贴板的功能
            // case R.id.stick_address_icon:
            // if (mStickAddressContent.getVisibility() == View.VISIBLE) {
            // mStickLine.setVisibility(View.GONE);
            // mStickAddressContent.setVisibility(View.GONE);
            // mStickImage.setImageResource(R.drawable.drawer_down);
            // } else {
            // mStickLine.setVisibility(View.VISIBLE);
            // mStickAddressContent.setVisibility(View.VISIBLE);
            // mStickImage.setImageResource(R.drawable.drawer_up);
            // }
            // break;
        }
    }

    private String address;

    // 选择popupwindow里面的位置、回调
    public void onSelectLocation(SameCityHistoryBean detailsBean) {
        //省市区展示
        ReceiverBean bean = new ReceiverBean();
        bean.setProvince(detailsBean.getProvince());
        bean.setProvinceId(detailsBean.getProvinceId());
        bean.setCity(detailsBean.getCity());
        bean.setCityId(detailsBean.getCityId());
        bean.setDistrict(detailsBean.getDistrict());
        bean.setDistrictId(detailsBean.getDistrictId());
        bean.setAddress(detailsBean.getAddress() + detailsBean.getBuildName());
        bean.setBuildName(detailsBean.getBuildName());
        setAddress(bean);
        //        String regex = "(.+?省)?.+?市.+?区";
        //        String result = details.replaceAll(regex, "");
        //详细地址
        //        mAddressDetailEdit.setText(result);
    }

    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            // 定位
            case MsgID.location_receiver_new:
                Intent service = new Intent();
                BDLocation location = (BDLocation) msg.obj;
                if (location != null && !isEmpty(location.getCity())) {
                    showLoadingDialog("正在查询");
                    AppHttp.getInstance().getAddressSameCity(location.getLongitude(), location.getLatitude());
                } else {
                    cancelLoadingDialog();
                    showToast("定位失败");
                }
                //                address = location.getProvince() + " " + location.getCity() + " " + location.getDistrict();
                //                service.setClass(getActivityContext(), BaiduSearchService.class);
                //                service.putExtra("latitude", location.getLatitude());
                //                service.putExtra("longitude", location.getLongitude());
                //                getActivityContext().startService(service);
                break;
            // 按照经纬度查询地址列表
            //            case MsgID.location_geocoder:
            //                cancelLoadingDialog();
            //                @SuppressWarnings("unchecked")
            //                ArrayList<LocationBean> items = (ArrayList<LocationBean>) msg.obj;
            //                ArrayList<LocationBean> copyItems = new ArrayList<LocationBean>(items);
            //                DialogMgr.showLocationList(this, copyItems, R.id.receiver_new_sure);
            //                //
            //                stopService(BaiduSearchService.class);
            //                break;
            // 查询地址上门地址
            case MsgID.same_city_address_location:
                cancelLoadingDialog();
                final AppResult<SameCityHistoryBean> result1 = JSON.parseList(msg.obj, SameCityHistoryBean.class);
                getActivityContext().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result1.isSuccess()) {
                            DialogMgr.showLocationList(ReceiverNewFragment.this, result1.getResultList(), R.id.receiver_new_sure);
                        } else {
                            showToast(result1.getMessage());
                        }
                    }
                });
                return true;
            // 新增收件人--关联订单
            case MsgID.receiver_add_new:
                cancelLoadingDialog();
                AppResult<?> appResult = JSON.parser(msg.obj);
                switch (appResult.getStatus()) {
                    case 1:
                        // 包裹Id
                        try {
                            Object result = appResult.getResult();
                            String id = result.toString().substring(1, result.toString().length() - 1);
                            receiver.setParcelId(Str.parseInt(id));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        getActivity().finish();
                        break;
                    case 0:
                        showToast(appResult.getMessage());
                        break;
                }
                break;
            // 从收件人历史列表里编辑收件人
            case MsgID.receiver_edit_history2new:
                ReceiverBean item = (ReceiverBean) msg.obj;
                mNameEdit.setText(item.getName());
                mMobileEdit.setText(null);
                mMobileEdit.setText(item.getPhone());
                setAddress(item);
                mAddressDetailEdit.setText(item.getAddress());
                return false;// 多个地方用,注意返回false
            //从服务器获取智能填写的联系人相关信息
            case MsgID.get_receiver_info_parse:
                cancelLoadingDialog();
                final AppResult<ReceiverInfoBean> result = JSON.parser(msg.obj, ReceiverInfoBean.class);
                getActivityContext().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (result.isSuccess()) {
                            ReceiverBean receiver = new ReceiverBean();
                            ReceiverInfoBean bean = result.getResult();
                            if (bean == null) {
                                showToast("填写失败!");
                                return;
                            }
                            if (Str.isNotEmpty(bean.getProvince()) && Str.isNotEmpty(bean.getProvinceId())
                                    && Str.isNotEmpty(bean.getCity()) && Str.isNotEmpty(bean.getCityId())
                                    && Str.isNotEmpty(bean.getDistrict()) && Str.isNotEmpty(bean.getDistrictId())) {
                                receiver.setProvince(bean.getProvince());
                                receiver.setProvinceId(bean.getProvinceId());
                                receiver.setCity(bean.getCity());
                                receiver.setCityId(bean.getCityId());
                                receiver.setDistrict(bean.getDistrict());
                                receiver.setDistrictId(bean.getDistrictId());
                                if (Str.isNotEmpty(bean.getAddress())) {
                                    receiver.setAddress(bean.getAddress());
                                }

                                String address = bean.getProvince() + " " + bean.getCity() + " " + bean.getDistrict();
                                mAddressEdit.setText(address);
                                setAddress(receiver);
                            }
                            if (Str.isNotEmpty(bean.getName())) {
                                mNameEdit.setText(bean.getName());
                            }
                            if (Str.isNotEmpty(bean.getPhone())) {
                                mMobileEdit.setText(bean.getPhone());
                            }
                            if (Str.isNotEmpty(bean.getAddress())) {
                                mAddressDetailEdit.setText("");
                                mAddressDetailEdit.setText(bean.getAddress());
                                mAddressDetailEdit.setSelection(mAddressDetailEdit.getText().length());
                            }
                        } else {
                            showToast(result.getMessage());
                        }
                    }
                });
                return false;
        }
        return super.handleMessage(msg);
    }

    private void setAddress(ReceiverBean item) {
        try {
            if (item == null) {
                return;
            }
            mAddressEdit.setText(item.getProvince() + " " + item.getCity() + " " + item.getDistrict());
            if (Str.isNotEmpty(item.getAddress())) {
                mAddressDetailEdit.setText("");
                mAddressDetailEdit.setText(item.getAddress());
                mAddressDetailEdit.setSelection(mAddressDetailEdit.getText().length());
            }
            // 寄件人
            if (isReceiver == false) {
                // 寄件人默认不保存, 只有当点击确认按钮以后才保存
                SenderBean sender = receiver.getSender();
                if (sender == null) {
                    sender = new SenderBean();
                }
                sender.copyRegion(item);
                this.receiver.setSender(sender);
                // sender.setProvince(item.getProvince());
                // sender.setCity(item.getCity());
                // sender.setDistrict(item.getDistrict());
                // this.receiver.setSender(sender);
            } else {// 收件人
                this.receiver.copyRegion(item);
                textWatcher.afterTextChanged(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        if (isCurrentShow()) {
            if (isReceiver) {
                if (mAddressDetailEdit.getText().toString().length() > 50) {
                    receiver.setAddress(mAddressDetailEdit.getText().toString().substring(0, 50));
                } else {
                    receiver.setAddress(mAddressDetailEdit.getText().toString());
                }
                if (mNameEdit.getText().toString().length() > 10) {
                    receiver.setName(mNameEdit.getText().toString().substring(0, 10));
                } else {
                    receiver.setName(mNameEdit.getText().toString());
                }
                if (mMobileEdit.getText().toString().length() > 11) {
                    receiver.setPhone(mMobileEdit.getText().toString().substring(0, 11));
                } else {
                    receiver.setPhone(mMobileEdit.getText().toString());
                }
            } else {
                //寄件人
                SenderBean senderBean = receiver.getSender();
                if (senderBean == null) {
                    senderBean = new SenderBean();
                    receiver.setSender(senderBean);
                }
                if (mAddressDetailEdit.getText().toString().length() > 50) {
                    senderBean.setAddress(mAddressDetailEdit.getText().toString().substring(0, 50));
                } else {
                    senderBean.setAddress(mAddressDetailEdit.getText().toString());
                }
                if (mNameEdit.getText().toString().length() > 10) {
                    senderBean.setName(mNameEdit.getText().toString().substring(0, 10));
                } else {
                    senderBean.setName(mNameEdit.getText().toString());
                }
                if (mMobileEdit.getText().toString().length() > 11) {
                    senderBean.setPhone(mMobileEdit.getText().toString().substring(0, 11));
                } else {
                    senderBean.setPhone(mMobileEdit.getText().toString());
                }
            }
        }
        super.onPause();
    }

    /**
     * {@link ChooseAreaActivity#showAreaLayout}
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 设置地址
        if (resultCode == Activity.RESULT_OK && requestCode == 1001) {
            ReceiverBean item = (ReceiverBean) data.getSerializableExtra("item");
            setAddress(item);
        }
        // 手机通讯录
        else if (resultCode == Activity.RESULT_OK && requestCode == 1002) {
            if (data == null) {
                return;
            }
            try {
                // content://com.android.contacts/contacts/lookup/1885r7-45D643445A61896E3D23/7
                String[] phones = new ContactUtils().getContactPhone(getActivityContext(), data.getData());
                mNameEdit.setText(phones[0]);
                mMobileEdit.setText(phones[1]);
                //
                MobclickAgent.onEvent(getActivityContext(), "联系人From通讯录");
            } catch (Exception e) {
                e.printStackTrace();
                showToast("获取联系人失败");
            }
        }
        // 选择快递公司
//        else if (resultCode == Activity.RESULT_OK && requestCode == 1004) {
//            String expressCompanyId = data.getStringExtra("companyId");
//            String expressCompanyName = data.getStringExtra("expressCompanyName");
//            String totalPrice = data.getStringExtra("totalPrice");
//            String weight = data.getStringExtra("weight");
//            this.receiver.setExpressCompanyId(expressCompanyId);
//            this.receiver.setExpressCompanyName(expressCompanyName);
//            this.receiver.setExpressPrice(totalPrice);
//            this.receiver.setWeight(weight);
//            // 标准寄件
//            if (receiver.getType() == 0) {
//                Intent intent = new Intent();
//                intent.setClass(getActivityContext(), LocationMgrActivity.class);
//                startActivity(intent);
//            }
//        }
        else if (requestCode == 1003 && resultCode == Activity.RESULT_OK) {//选取图片后返回路径,暂时不用
            Uri uri = data.getData();
            Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                picPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                Log.i("leung", picPath);
                if (!Str.isEmpty(picPath)) {
                    handlerLoadImage(picPath);
                }
            }

        } else if (resultCode == Activity.RESULT_OK && 1006 == requestCode) {//选取要识别的图片
            String capturePath = data.getStringExtra("file");
            if (!Str.isEmpty(capturePath)) {
                picPath = capturePath;
                handlerLoadImage(picPath);
                recognizeGeneralOCR(picPath);
            }
        } else if (requestCode == 1005 && resultCode == Activity.RESULT_OK) {
            boolean reload = data.getBooleanExtra("needreload", false);
            if (reload) {
                //                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //                startActivityForResult(intent, 1003);
                Intent intent = new Intent(getActivityContext(), ReceiverCameraActivity2.class);
                startActivityForResult(intent, 1006);
            }

        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void handlerLoadImage(String picPath2) {
        mThumbnailItem.setVisibility(View.VISIBLE);
        Bitmap imageThumbnail = BitmapUtil.getImageThumbnail(picPath2, 150, 150);
        ImageView thumbImag = (ImageView) findViewById(R.id.thumb_img);
        thumbImag.setImageBitmap(imageThumbnail);

        int height = Utils.dpToPx(142, getResources()) + Utils.dpToPx(245, getResources());//Utils.dpToPx(110, getResources());//findViewById(R.id.thumbnail_view1).getHeight()
        layoutParams.height = height;
        mInputLayout.setLayoutParams(layoutParams);
        Animator.scaleY(mInputLayout, new Callback() {
            @Override
            public void execute(Object... result) {
                mScrollView.scrollTo(0, mScrollView.getBottom());
            }
        }, 0, height);
    }

    /**
     * 通用文字识别
     */
    private void recognizeGeneralOCR(String picPath) {
        showLoadingDialog(null);
        // 通用文字识别参数设置
        GeneralBasicParams param = new GeneralBasicParams();
        param.setDetectDirection(true);
        param.setImageFile(new File(picPath));
        if (!hasGotToken) {
            showToast("识别授权失败");
            return;
        }
        // 调用通用文字识别服务
        OCR.getInstance().recognizeGeneralBasic(param, new OnResultListener<GeneralResult>() {
            @Override
            public void onResult(GeneralResult result) {
                cancelLoadingDialog();
                // 调用成功，返回GeneralResult对象
                for (WordSimple wordSimple : result.getWordList()) {
                    // wordSimple不包含位置信息
                    stringBuilder.append(wordSimple.getWords());
                    stringBuilder.append(",");
                }
                mStickAddressContent.setText(stringBuilder.toString());
                mStickAddressContent.setSelection(mStickAddressContent.getText().toString().length());
            }

            @Override
            public void onError(OCRError error) {
                // 调用失败，返回OCRError对象
                cancelLoadingDialog();
                showToast("识别失败");
            }
        });
    }

    /**
     * 信息提示框
     */
    private void showReceiverInformation(final String content) {
        final AppDialog dialog = new AppDialog(getActivity());
        StringBuilder sb = new StringBuilder();
        sb.append("您是否想将\"");
        sb.append(content);
        sb.append("\"添加到智能输入面板?");
        dialog.setContent(sb.toString());
        dialog.setConfirmClickListener("确定", new OnClickListener() {
            @Override
            public void onClick(View v) {
                mStickAddressContent.setText(content);
                dialog.dismiss();
            }
        });
        dialog.setCancelClickListener("取消", null);
        dialog.show();
    }

    /**
     * 点击语音录入
     */
    private void speekInputData() {
        final TextView voiceInputTV = (TextView) findViewById(R.id.voice_input_tv);
        final String json = "{\"accept-audio-data\":false,\"disable-punctuation\":false,\"accept-audio-volume\":true,\"pid\":1537}";
        voiceInputTV.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    voiceInputTV.getParent().getParent().requestDisallowInterceptTouchEvent(true);
                    mEventManager.send(SpeechConstant.ASR_START, json, null, 0, 0);
                    initBerzerParam(true);
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    initBerzerParam(false);
                    voiceInputTV.getParent().getParent().requestDisallowInterceptTouchEvent(false);
                    mEventManager.send(SpeechConstant.ASR_STOP, null, null, 0, 0);
                    mVoiceInputLayout.setVisibility(View.GONE);
                    findViewById(R.id.bottom_layout).setVisibility(View.VISIBLE);
                }
                return true;
            }
        });
    }

    /**
     * 语音录入回调
     *
     * @param name
     * @param params
     * @param data
     * @param offset
     * @param length
     */
    @Override
    public void onEvent(String name, String params, byte[] data, int offset, int length) {
        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_READY)) {
            // 引擎就绪，可以说话，一般在收到此事件后通过UI通知用户可以说话了
            mSpeekContent = "";
        }
        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_VOLUME)) {
            //音量大小回调
            if (Str.isNotEmpty(params)) {
                int volume = JsonParser.parse(params, "volume-percent", Integer.class);
                mSonicSensorView.setVoiceLevel(mSonicSensorView.formatVoiceSize(volume));
            }
        }
        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {
            //讲话中回调
            mSpeekContent = params;
        }
        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_FINISH)) {
            // 识别结束
            if (isEmpty(params)) {
                Alert.toastWithImage("无法识别内容\n请手动填写", R.drawable.self_speek_error, null);
            } else {
                int error = JsonParser.parse(params, "error", Integer.class);
                if (error == 0) {
                    if (isEmpty(mSpeekContent)) {
                        Alert.toastWithImage("无法识别内容\n请手动填写", R.drawable.self_speek_error, null);
                    } else {
                        mSpeekContent = JsonParser.parse(mSpeekContent, "best_result", String.class);
                        if (Str.isNotEmpty(mSpeekContent)) {
                            Alert.toastWithImage("录入成功\n可手动矫正保证填写正确", R.drawable.self_speek_correct, null);
                            stringBuilder.append(mSpeekContent);
                            mStickAddressContent.setText(stringBuilder.toString());
                            mStickAddressContent.setSelection(mStickAddressContent.getText().toString().length());
                            Log.d("11111", "语音录入内容:" + stringBuilder.toString());
                        } else {
                            Alert.toastWithImage("无法识别内容\n请手动填写", R.drawable.self_speek_error, null);
                        }
                    }
                } else {
                    Alert.toastWithImage("无法识别内容\n请手动填写", R.drawable.self_speek_error, null);
                }
            }
        }
    }

    //重写父类方法，因智能填写需要直角

    /**
     * @param button
     * @param enable
     * @param type   0 确认提交  1 智能填写按钮
     */
    public void setButtonEnableStyle(Button button, boolean enable, int type) {
        int bottom = button.getPaddingBottom();
        int top = button.getPaddingTop();
        int right = button.getPaddingRight();
        int left = button.getPaddingLeft();
        if (enable) {
            if (type == 1) {
                button.setBackgroundResource(R.drawable.self_receiver_input_ffe226_shape);
            } else {
                button.setBackgroundResource(R.drawable.app_button_selector_no_corners);
                button.setTextColor(getResources().getColorStateList(R.color.app_buttoncolor_selector));
            }
        } else {
            if (type == 1) {
                button.setBackgroundResource(R.drawable.self_receiver_input_cacaca_shape);
            } else {
                button.setBackgroundResource(R.drawable.app_button_bg_no_corners_disable);
                button.setTextColor(getResources().getColor(R.color.white));
            }
        }
        button.setPadding(left, top, right, bottom);
    }

    @Override
    public void onDestroy() {
        if (mEventManager != null) {
            mEventManager.send(SpeechConstant.ASR_CANCEL, "{}", null, 0, 0);
            mEventManager.unregisterListener(this);
            mEventManager = null;
        }
        if (OCR.getInstance() != null) {
            OCR.getInstance().release();
        }
        super.onDestroy();
    }
}
